<template>
  <div>
    <div class="header">
      <span class="text1">Fault Diagnosis</span>
      <el-button type="text" class="header-text2" @click="goOff()">return</el-button>
    </div>
    <div class="box">
      <div class="box1">
        <div class="discern1">
          <img class="d1" src="../assets/img/discern1.png" alt="" >
          <p class="text2">Upload picture function</p>
          <p class="text3">By uploading pictures and input related information, analyze and output picture information.</p>
        </div>
        <div class="manage1">
          <div style="font-size: 15px;color:#515a6e;padding-top: 10px;">
            Please upload a 225 x 225 pixel image in png or jpg format. After uploading, the details of the image will be displayed in the table below.
          </div>
          <div class="card-body text-center">
            <img :src="previewImageUrl" class="rounded img-thumbnail mb-3 preview-image" style="height: 200px;width: 200px">
            <el-form class="form-group" :model="form" style="margin-left: 40px">
              <el-form-item label="Select indicator diagram picture:" class="choose">
                <input type="file" ref="fileInput" accept="image/*" @change="uploadImage">
              </el-form-item>
            </el-form>
            <el-button type="primary" class="mt-3" id="identifyBtn" @click="submitImage" style="margin-left: 40px">Upload now</el-button>
          </div>
          <el-table :data="lists" stripe style="width: 100%">
            <el-table-column prop="result" label="Result" />
            <el-table-column label="Picture" width="250" prop="image">
              <template #default="scope">
                <el-image
                    style="width: 100px; height: 100px"
                    :src=" 'data:image/png,image/jpg;base64,'+ scope.row.image"
                    fit="cover"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="box1">
        <div class="discern1">
          <img class="d1" src="../assets/img/discern2.png" alt="" >
          <p class="text2">Input file function</p>
          <p class="text3">Analyze and organize the analysis information of the output file through the input file.</p>
        </div>
        <div class="manage2">
          <div style="font-size: 15px;color:#515a6e;padding-top: 10px;">
            Please drag the file to the white box or click the Upload Now button to upload the file. The file must be in xlsx,xlx or csv format.
            Please go to the machine management platform for detailed test results
          </div>
          <div class="document">
            <el-upload drag
                       name="file"
                       :limit=limitNum
                       :auto-upload="false"
                       accept=".xlsx,.xlx,.csv"
                       :action="UploadUrl()"
                       :before-upload="beforeUploadFile"
                       :on-change="fileChange"
                       :on-exceed="exceedFile"
                       :on-success="handleSuccess"
                       :on-error="handleError"
                       :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">Drag the file here, or<em>Click to upload</em></div>
              <div class="el-upload__tip" slot="tip">The file does not exceed 10M</div>
            </el-upload>
            <br/>
            <el-button  type="primary" @click="uploadFile" style="margin-left: 250px" >Upload now</el-button>
            <el-button style="width: 100px">Cancel</el-button>
          </div>
          <p class="check">Please go to the machinery management platform to check the test results</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "discern2",
  data(){
    return {
      form: {
        image: null
      },
      lists: [],
      previewImageUrl: 'https://via.placeholder.com/225',
      resultData: [],
      labelPosition: 'top',
      formLabelAlign: {
        name: '',
        region: '',
        type: ''
      },
      limitNum: 1,  // 上传excell时，同时允许上传的最大数
      fileList: [],   // excel文件列表
    }
  },
  methods:{
    uploadImage(event) {
      this.imageFile = event.target.files[0];
      this.previewImageUrl = URL.createObjectURL(this.imageFile);
    },
    goOff(){
      this.$router.go(-1)
    },
    getlist(){
      // 开始加载loading
      //   let loading = this.$loading({
      //   lock: true, //lock的修改符--默认是false
      //   text: "拼命加载中，请稍候...", //显示在加载图标下方的加载文案
      //   background: "rgba(0,0,0,0.8)", //遮罩层颜色
      //   spinner: "el-icon-loading", //自定义加载图标类名
      // });
      axios.get('/user/getImageMessage')
          .then(response => {
            // 处理接收到的JSON数据
            console.log("data",response.data)
            this.lists=response.data
            // loading.close()
            console.log(this.image)
            console.log(this.lists)
          })
          .catch(error => {
            console.error('Error:', error);
          });
    },
    submitImage() {
      if (this.imageFile) {
        const formData = new FormData();
        formData.append('file', this.imageFile);
        axios.post('/user/identify', formData)
            .then(response => {
              this.getlist();
              const uploadTime = new Date();
              this.resultData.push({
                result: response.data.result,
                time: uploadTime,
              });// 从后端返回数据中获取 result 属性
              console.log(response.data.result);
              // 在这里处理后端返回的结果
            })
            .catch(error => {
              console.error(error);
            });
      }
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`);
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      console.log(file.raw);
      this.fileList.push(file.raw) ;
      console.log(this.fileList);
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      console.log('before upload');
      console.log(file);
      let extension = file.name.substring(file.name.lastIndexOf('.')+1);
      let size = file.size / 1024 / 1024;
      if(extension !== 'xlsx||xlx||csv') {
        this.$message.warning('只能上传后缀是.xlsx或.xlx的文件');
      }
      if(size > 10) {
        this.$message.warning('文件大小不得超过10M');
      }
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.$message.success('文件上传成功');
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message.error('文件上传失败');
    },
    UploadUrl:function(){
      // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
      return ""
    },
    async uploadFile() {
      const formData = new FormData();
      const file = this.fileList[0];
      formData.append('file',file);
      try {
        const response = await axios.post('/user/identify', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        this.$message.success('文件上传成功');
        // this.$router.push('/manage')
        // 处理上传成功的逻辑
      } catch (error) {
        this.$message.error('文件上传失败');
        console.error(error);
        // 处理上传失败的逻辑
      }
    }
  }
}
</script>

<style scoped>
.text1{
  margin-left:160px;
  position: absolute;
  top:20px;
}
.header-text2{
  margin-left: 63em;
  padding-top: 1.6em;
  font-size: 20px;
  color: #515a6e;
}
.header{
  height: 70px;
  background-color:rgba(151, 171, 215, 0.12) ;
  margin-bottom: 20px;

}
.box{
  display: -webkit-flex;
  display: flex;
  margin-left: 10px;
}

.box1 {
  background-color:white;
  width: 730px;
  height:700px;
  margin-right: 20px;
}
.d1{
  width: 70px;
  height: 70px;
}
.discern1{
  padding-top:10px;
  padding-left: 20px;
  height: 145px;
  background-color: #007BFF;
  border-radius: 10px 10px 0 0;
}
.text2{
  font-weight: bold;
  color: white;
  font-size: 20px;
  padding-top: 6px;
}
.text3{
  color:white;
  font-size: 15px;
  padding-top: 6px;
}
.manage1{
  background-color:rgba(151, 171, 215, 0.12);
  height: 500px;
  width: 730px;
  border-radius: 0 0 10px 10px;
}
.manage2{
  background-color:rgba(151, 171, 215, 0.12);
  height: 500px;
  width: 730px;
  border-radius: 0 0 10px 10px;
}
.rounded {
  margin-top: 20px;
}
.mt-4{
  margin-left: 160px;
  margin-right: 150px;
}
.mt-3{
  position: relative;
  top:-100px;
  left:170px;
  width: 100px;

}
.choose {
  position: relative;
  top: -100px;
  left: 170px;
}
.check{
  text-align: center ;
  margin-top:30px;
  color:#515a6e;
  font-size:20px;
}
.document {
  padding: 60px 10px 0 10px;

}

</style>
